<template>
  <!-- aa -->
  <div>
    <el-card v-loading="loading">
      <el-row v-if="content">
        <el-button
          type="success"
          v-if="userStatus == 0 && userStepId == 0"
          @click="handleReloadTable"
          >重载数据</el-button
        >
        <el-button type="success" @click="saveData" v-if="userStatus == 0"
          >保存</el-button
        >
        <el-button type="success" @click="submitData" v-if="userStatus == 0">
          提交
        </el-button>
        <el-button
          type="success"
          @click="returnWrite"
          v-if="userStatus == 0 && userStepId > 0"
        >
          退回给填报员
        </el-button>
        <el-button
          type="success"
          v-if="userStatus != 0 || userStepId != 0"
          @click="showRecord"
          >流程记录</el-button
        >
        <el-button type="success" @click="printDateForm">打印</el-button>
        <el-button @click="selectSampleShow" type="success">选样</el-button>
      </el-row>
      <el-scrollbar :height="textHeight" ref="textScrollbarRef">
        <div
          v-html="content"
          id="dataForm"
          @contextmenu.prevent="openMenu($event)"
          @click="tdColor($event)"
          @dblclick="trColor($event)"
        ></div>
      </el-scrollbar>
    </el-card>
    <!-- 流程记录 -->
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      v-model="recordOpen"
      :title="recordTitle"
      width="950"
    >
      <el-table :data="recordList" v-loading="loadingRecord" max-height="60vh">
        <el-table-column label="步骤" align="center">
          <template #default="scope">
            <span v-if="scope.row.userStepId == 0">现场填报</span>
            <span v-if="scope.row.userStepId == 1">复核</span>
            <span v-if="scope.row.userStepId == 2">审核</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="nickName" align="center" />
        <el-table-column label="开始时间" prop="createTime" align="center" />
        <el-table-column label="结束时间" prop="finishTime" />
        <el-table-column label="状态">
          <template #default="scope">
            <span v-if="scope.row.userStatus == 0">未完成</span>
            <span v-if="scope.row.userStatus == 1">已完成</span>
            <span v-if="scope.row.userStatus == 2">退回</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="recordOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <ul
      v-show="visible"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="addTr(contextmenuVal)" v-if="showTr(contextmenuVal)">
        <Plus style="width: 1em; height: 1em" /> 增加行
      </li>
      <li
        @click="delTr(contextmenuVal)"
        v-if="showTr(contextmenuVal)"
        :style="'cursor:' + cursorStyle"
      >
        <Minus style="width: 1em; height: 1em" /> 删除行
      </li>
      <li @click="downWrite(contextmenuVal)" v-if="showDown(contextmenuVal)">
        <Bottom style="width: 1em; height: 1em" /> 向下填充
      </li>
      <li
        v-for="item in childComponentList"
        @click="byConditionDownWrite(contextmenuVal, item.componentId)"
        v-if="showDown(contextmenuVal)"
      >
        <Bottom style="width: 1em; height: 1em" /> 根据{{ item.componentName }}向下填充
      </li>
    </ul>
    <el-button
      @click="upClick"
      style="position: absolute; bottom: 40px; right: 40px; z-index: 9999"
      type="success"
      link
    >
    </el-button>
    <selectSample ref="selectSampleRef" @handleDefine="handleDefine"></selectSample>
  </div>
</template>

<script setup>
import { postContent, getMarkList, delContent } from "@/api/cyCheck/filling";
import {
  getTableDataByTask,
  getTemplateContent,
  addTableData,
  approveData,
  returnWriteData,
  reloadTable,
  userRecordList,
} from "@/api/myTask/myTask";
import { sampleToLab } from "@/api/sampleManage/sampleGet";

import selectSample from "./selectSample.vue";
import "jquery-ui-dist/jquery-ui";
import "jquery-ui-dist/jquery-ui.min.css";
import "@/components//popover/jquery.webui-popover.min.js";
import "@/components/popover/jquery.webui-popover.min.css";
import "@/plugins/jquery.jqprint-0.3.js";
import "@/components/datepicker/datepicker.css?t=1";
import "@/components/datepicker/moment.min.js";
import "@/components/datepicker/datepicker.all.js";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();

const content = ref("");
const myId = ref("");
const tFId = ref("");
const tableId = ref("");
const loading = ref(false);
//用户状态 0：待办 1已办
const userStatus = ref(1);
//步骤id
const userStepId = ref(0);
const recordOpen = ref(false);
const recordTitle = ref("流程记录");
const recordList = ref([]);
const loadingRecord = ref(false);

const props = defineProps({
  myId: {
    type: String, //参数类型
  },
});

const emits = defineEmits(["define"]);
function handleDefine(val) {
  myId.value = val;
  showTable();
  emits("define");
}

const cursorStyle = ref("pointer");

function showTable() {
  loading.value = true;
  if (myId.value) {
    getTableDataByTask(myId.value).then((res) => {
      if(!res.data){
        return;
      }
      tFId.value = res.data.tFId;
      userStatus.value = res.data.userStatus;
      userStepId.value = res.data.userStepId;
      content.value = res.data.content;
      childComponentList.value = res.data.childComponentList;
      loading.value = false;
      nextTick(() => {
        $("#dataForm").find("td").removeAttr("nowrap");
        if (userStatus.value == 0) {
          initPopover();
          $(".datepicker_mm").datePicker({
            format: "YYYY-MM-DD HH:mm",
          });
          $(".datepicker").datePicker({
            format: "YYYY-MM-DD",
          });
          $(".datepicker1").datePicker({
            format: "YYYY年MM月DD日",
          });
        }
        setFixerTr();
        if ($("tr.childTr").length == 1) {
          cursorStyle.value = "not-allowed";
        } else {
          cursorStyle.value = "pointer";
        }
      });
      getHeight();
    });
  } else {
    getTemplateContent(tableId.value).then((res) => {
      // content.value = '<table style="border-collapse: collapse; width: 100%;" border="1"><tbody><tr><td style="width: 50.0556%;">测试</td><td style="width: 50.0556%;"><input type="date" style="width: 100%;border:0px"/></td></tr></tbody></table>'
      content.value = res.data.content;
      childComponentList.value = res.data.childComponentList;
      loading.value = false;
      nextTick(() => {
        $(".datepicker_mm").datePicker({
          format: "YYYY-MM-DD HH:mm",
        });
        $(".datepicker").datePicker({
          format: "YYYY-MM-DD",
        });
        $(".datepicker1").datePicker({
          format: "YYYY年MM月DD日",
        });
        setFixerTr();
      });
      getHeight();
    });
  }
}

//设置固定行为表头或表尾
function setFixerTr() {
  let $fixedHead = $("tr.fixed-head");
  let height = 0;
  $fixedHead.each(function (i) {
    $(this).css("top", height + "px");
    height += $(this).height();
  });
  let $fixedFoot = $("tr.fixed-foot");
  height = 0;
  for (let i = $fixedFoot.length - 1; i >= 0; i--) {
    let $this = $fixedFoot.eq(i);
    $this.css("bottom", height + "px");
    height += $this.height() + 1;
  }
}
function getData() {
  let $form = $("#dataForm");
  let jsonData = {};
  $form.find(".component").each(function () {
    if (!$(this).parents("tr:first").hasClass("childTr")) {
      //排除子表行控件
      let jsonValue = getComponentData($(this));
      if (jsonValue) {
        Object.assign(jsonData, jsonValue);
      }
    }
  });
  //查询子表的控件数据
  let childJsonArray = [];
  $form.find("tr.childTr").each(function () {
    let childJson = {};
    if ($(this).attr("id")) {
      childJson.id = $(this).attr("id");
    }
    if ($(this).data("id")) {
      Object.assign(childJson, eval($(this).data("id")));
    }
    if (!jsonData.childWrite && $(this).hasClass("child-write")) {
      //child-write：自由填写标识
      jsonData.childWrite = true;
    }
    let $components = $(this).find(".component");
    $components.each(function () {
      let jsonValue = getComponentData($(this));
      if (jsonValue) {
        Object.assign(childJson, jsonValue);
      }
    });
    if (!$.isEmptyObject(childJson) && $components.length > 0) {
      //判断json对象是否为空
      childJsonArray.push(childJson);
    }
  });
  if (childJsonArray.length > 0) {
    jsonData.childDataList = childJsonArray;
  }
  jsonData.myId = myId.value;
  jsonData.tFId = tFId.value;
  return jsonData;
}
/**
 * 保存数据
 */
function saveData() {
  let jsonData = getData();
  //保存数据
  addTableData(jsonData).then((res) => {
    proxy.$modal.msgSuccess("保存成功！");
    sampleToLab(myId.value).then((res) => {});
  });
}

function submitData() {
  let jsonData = getData();
  proxy.$modal.confirm("确认要提交吗？").then(function () {
    approveData(jsonData).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      showTable(myId.value);
    });
  });
}

function returnWrite() {
  let jsonData = getData();
  proxy.$modal.confirm("确认要退回给填报员吗？").then(function () {
    returnWriteData(jsonData).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      showTable(myId.value);
    });
  });
}

function showRecord() {
  recordOpen.value = true;
  loadingRecord.value = true;
  userRecordList(myId.value).then((res) => {
    recordList.value = res.data;
    loadingRecord.value = false;
  });
}

/**
 * 重新加载模板
 */
function handleReloadTable() {
  if (!myId.value) {
    proxy.$modal.msgError("未找到表单id！");
    return false;
  }
  proxy.$modal.confirm("确定要重载数据吗？").then(function () {
    reloadTable(myId.value).then((res) => {
      showTable(res.data);
    });
  });
}
function getComponentData($that) {
  let name = $that.attr("name");
  if (!name) return null;
  let json = {};
  let jsonValue = "";
  let $componentName = $that.find("[name=" + name + "]");
  if ($componentName.length == 0) {
    $componentName = $that.find("[data-id='" + name + "']");
  }
  if ($componentName.length == 0) {
    jsonValue = $.trim($that.text());
  } else {
    let nodeType = $componentName[0].nodeName;
    let type = $componentName.attr("type");
    if (nodeType && nodeType.toLowerCase() == "select") {
      jsonValue = $componentName.val();
      json[name + "t"] = $componentName.find("option:selected").text();
    } else if (type && (type == "checkbox" || type == "radio")) {
      let $checkbox = $that.find("input[data-id='" + name + "']:checked");
      if ($checkbox.length == 0) return null;
      let values = "";
      let texts = "";
      $checkbox.each(function () {
        values += "," + this.value;
        texts += "、" + $(this).next().text();
      });
      jsonValue = values.substring(1);
      json[name + "t"] = texts.substring(1);
    } else if ($componentName.hasClass("sign") && $componentName.is(":visible")) {
      //签字控件并且显示
      jsonValue = $componentName.attr("src");
    } else {
      jsonValue = $.trim($componentName.val());
    }
  }
  //if (jsonValue.length == 0) return null;
  json[name] = jsonValue;
  return json;
}

// ---------------------------------右击列表----------------------------------------
const left = ref(0);
const top = ref(0);
const visible = ref(false);
const contextmenuVal = ref({});
const childComponentList = ref([]);
// 右击事件
function openMenu(e) {
  if (userStatus.value != 0 || userStepId.value != 0) return;

  let $target = $(e.target);
  let isNext = false;
  if (e.target.nodeName.toLowerCase() != "td") {
    $target = $target.parents("td:first");
    isNext = true;
  }
  if (!$target.parents("tr:first").hasClass("childTr")) return;
  if (!isNext && $target.prop("contenteditable") === "false") return;
  // 右击加背景颜色
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  $target.addClass("bgcTdr");

  left.value = e.clientX - 330;
  top.value = e.clientY - 140;
  visible.value = true;

  if (
    e.target.nodeName.toLowerCase() == "td" &&
    e.target.childNodes[0]?.nodeName != "#text" &&
    e.target.childNodes[0]
  ) {
    contextmenuVal.value = e.target.childNodes[0];
    return;
  }

  contextmenuVal.value = e.target;
}

function closeMenu() {
  visible.value = false;
}

// 提示框
const markList = ref([]);
function initPopover() {
  var settings = {
    trigger: "dblclick",
    title: userStepId.value ? "添加标记" : "查看标记",
    width: 300,
    closeable: true,
    // 确定  取消  关闭  按钮显示隐藏
    showBtn: !!userStepId.value,
    style: "",
    padding: false,
    content: function (webuiPopover) {
      var markId = webuiPopover.$element.attr("markId");
      var content = "";
      for (const item of markList.value) {
        if (item.markId == markId) {
          content = item.content;
          break;
        }
      }
      return content;
    },
    onHide: function ($target, $element, btn) {
      return new Promise((resolve, reject) => {
        var markId = $element.attr("markId");
        if (btn == "confirm") {
          var content = $target.find(".webui-popover-content").text();
          var componentId = markId ? "" : $element.attr("name");
          var childFormId = markId ? "" : $element.parent().attr("id");
          if (!content) {
            proxy.$modal.msgError("请输入标记内容");
            return false;
          }
          let temp = {
            content: content,
            componentId: componentId,
            markId: markId,
            childFormId: childFormId,
            tFId: markId ? "" : tFId.value,
          };
          postContent(temp)
            .then((res) => {
              if (!markId) {
                $element.attr("markId", res.data);
                markList.value.push({ markId: res.data, content: content });
              } else {
                for (const item of markList.value) {
                  if (item.markId == markId) {
                    item.content = content;
                    break;
                  }
                }
              }
              $element.addClass("markColor");
              resolve(true);
            })
            .catch(() => {
              reject(false);
            });
        } else {
          if (!markId) {
            proxy.$modal.msgError("没有标记");
            return false;
          }
          delContent(markId)
            .then((res) => {
              proxy.$modal.msgSuccess("删除成功");
              markList.value = markList.value.filter((item) => {
                return item.markId != markId;
              });
              $element.removeAttr("markId");
              $element.removeClass("markColor");
              resolve(true);
            })
            .catch((res) => {
              reject(false);
            });
        }
      });
    },
  };
  if (userStatus.value === 0) {
    getMarkList({ myId: myId.value }).then((res) => {
      markList.value = res.data;
      for (const item of markList.value) {
        let $component;
        if (item.childFormId) {
          //子表行
          $component = $("#" + item.childFormId).find(
            "[name='" + item.componentId + "']"
          );
        } else {
          $component = $("[name='" + item.componentId + "']");
        }
        if ($component.length > 0) {
          $component.addClass("markColor").addClass("mark_");
          $component.attr("markId", item.markId);
        }
      }
      if (markList.value.length > 0 || userStepId.value == 1 || userStepId.value == 2) {
        $(".mark_").webuiPopover("destroy").webuiPopover(settings);
      }
    });
  }
}

// 向下填充
function downWrite(target) {
  let $s = $(target);
  let isChild = target.nodeName.toLowerCase() != "td";
  if (isChild) {
    let value = $s.val();
    let $target = $s.parents("td:first");
    var $tr = $target.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      var $t = $tr.find("[name='" + $target.attr("name") + "']");
      if ($t.length == 0) {
        break;
      }
      if ($t[1].type == "select-one") {
        var $options = $t[1].children;
        for (const index in $options) {
          if ($options[index].getAttribute("value") == value) {
            $options[index].setAttribute("selected", "");
            break;
          } else {
            $options[index].removeAttribute("selected");
          }
        }
      } else {
        var $e = $t[1];
        $e.value = value;
      }
    }
  } else {
    let value = $s.text();
    var $tr = $s.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      let $td = $tr.find("[name='" + $s.attr("name") + "']");
      if ($td.length == 0) {
        break;
      }
      $td.text(value);
    }
  }
}

// 根据条件向下填充
function byConditionDownWrite(target, cId) {
  let $s = $(target);
  let isChild = target.nodeName.toLowerCase() != "td";
  var clickValue = "";
  if (isChild) {
    for (const item of $s.parents("td:first").siblings()) {
      if (item.attributes.name.value == cId) {
        let $i = $(item);
        clickValue = $i.text();
        break;
      }
    }
    let value = $s.val();
    let $target = $s.parents("td:first");
    var $tr = $target.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      var $t = $tr.find("[name='" + $target.attr("name") + "']");
      if ($t.length == 0) {
        break;
      }
      if ($t[1].type == "select-one") {
        var $options = $t[1].children;
        for (const item of $tr[0].children) {
          if (item.attributes.name.value == cId) {
            let $i = $(item);
            if ($i.text() == clickValue) {
              for (const index in $options) {
                if ($options[index].getAttribute("value") == value) {
                  $options[index].setAttribute("selected", "");
                  break;
                } else {
                  $options[index].removeAttribute("selected");
                }
              }
            }
            break;
          }
        }
      } else {
        for (const item of $tr[0].children) {
          if (item.attributes.name.value == cId) {
            let $i = $(item);
            if ($i.text() == clickValue) {
              var $e = $t[1];
              $e.value = value;
            }
            break;
          }
        }
      }
    }
  } else {
    let value = $s.text();
    var $tr = $s.parents("tr:first");
    for (const item of $s.siblings()) {
      if (item.attributes.name.value == cId) {
        let $i = $(item);
        clickValue = $i.text();
        break;
      }
    }
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      let $td = $tr.find("[name='" + $s.attr("name") + "']");
      if ($td.length == 0) {
        break;
      }
      for (const item of $tr[0].children) {
        if (item.attributes.name.value == cId) {
          let $i = $(item);
          if ($i.text() == clickValue) {
            $td.text(value);
          }
          break;
        }
      }
    }
  }
}

// 增加行
function addTr(target) {
  var $target = $(target);
  var $tr = $target.parents("tr:first");
  let $clone = $tr.clone();
  $tr.after($clone);
  cursorStyle.value = "pointer";
}

// 删除行
function delTr(target) {
  if ($("tr.childTr").length == 1) {
    return;
  }
  var $target = $(target);
  var $tr = $target.parents("tr:first");
  $tr.remove();
  if ($("tr.childTr").length == 1) {
    cursorStyle.value = "not-allowed";
  } else {
    cursorStyle.value = "pointer";
  }
}

// 显示隐藏ul中的li
function showDown(e) {
  let $target = $(e);
  if (e.nodeName?.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  if (!$target.attr("sourcetype")) return false;
  let sourcetype = parseInt($target.attr("sourcetype"));
  let isWrite = parseInt($target.attr("isWrite"));
  if (sourcetype != 2 && sourcetype != 3 && isWrite != 1) return false;
  return true;
}

// 显示隐藏ul中的li
function showTr(e) {
  let $target = $(e);
  if (e.nodeName?.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  if (!$target.parents("tr:first").is(".child-write")) return false;
  return true;
}

// 单击td变色
function tdColor(e) {
  var $target = $(e.target);
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  if ($target[0].tagName.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  $target.addClass("bgcTdr");
}

// 双击tr变色
function trColor(e) {
  var $target = $(e.target);
  var $tr = $target.parents("tr:first");
  var $bgc = $(".bgcTdr");
  $bgc.removeClass("bgcTdr");
  $tr.addClass("bgcTdr");
}

watch(visible, (value) => {
  if (value) {
    document.body.addEventListener("click", closeMenu);
  } else {
    document.body.removeEventListener("click", closeMenu);
  }
});

// -------------------------------------------打印---------------------------------------------
function printDateForm() {
  $("#dataForm").jqprint({
    debug: false,
    importCSS: false,
    operaSupport: true,
    printContainer: true,
  });
}

// ---------------------------------------------回到顶部--------------------------------------
function upClick() {
  document.getElementById("dataForm").scrollIntoView();
}

// ----------------------------------------------选样-----------------------------------------
const selectSampleRef = ref(null);
function selectSampleShow() {
  selectSampleRef.value.openShow(myId.value);
}

const textHeight = ref(0);

function getHeight() {
  nextTick(() => {
    textHeight.value = proxy.getSubFileHeight(proxy, "textScrollbarRef");
  });
}

function isUpClick() {
  // document.getElementById("dataForm")
}
onMounted(() => {
  nextTick(() => {
    getHeight();
    window.addEventListener("resize", getHeight);
    isUpClick();
    window.addEventListener("resize", isUpClick);
  });
});
onUpdated(() => {
  nextTick(() => {
    getHeight();
    isUpClick();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getHeight);
  window.addEventListener("resize", isUpClick);
});

defineExpose({
  tableId,
  myId,
  showTable,
});
</script>

<style lang="scss" scoped>
#dataForm:deep(div.sign:hover .cha) {
  display: block !important;
}

#dataForm:deep(td) {
  word-break: break-all !important;
}

#dataForm:deep(.bgcTdr) {
  background-color: #d8fdde;
}

#dataForm:deep(.fixed-head),
#dataForm:deep(.fixed-foot) {
  position: sticky;
  background-color: #eee;
  z-index:1;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;

    &:hover {
      background: #eee;
    }
  }
}

#dataForm:deep(.markColor) {
  background: transparent url("/src/assets/images/report.gif") no-repeat scroll 0 0;
}
</style>
